package com.springbootee.Common.aop;


import com.springbootee.Common.Rest;
import com.springbootee.Common.RestException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;


@ControllerAdvice
public class ExeptionAdvie {
     @Autowired
     private HttpServletRequest request;
    /**
     *自动抛出异常
     * @param ex
     * @return
     * @throws Exception
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Rest<?> runtimeException(Exception ex) throws Exception{

        String result;
            //针对数据做出处理
        if (ex.getClass().getName().contains("org.springframework.validation") ||
            ex.getClass().getName().contains("org.springframework.context.support") ||
            ex.getClass().getName().contains("org.springframework.web.bind.MethodArgumentNotValidException") ||
            ex.getClass().getName().contains("javax.validation.constraints")){
            result =ex.getMessage();
            result=result.substring(result.lastIndexOf(
                    "default message [")+"default message [".length(),
                    result.lastIndexOf("]") - 1);
                return Rest.BAD_REQUEST(result);

        }
                ex.printStackTrace();
            //返回报错信息
            return Rest.ERROR(ex.getLocalizedMessage());
        }
    /**
     *手动抛出异常
     * @param ex
     * @retrun
     */
    @ExceptionHandler(RestException.class)
    @ResponseBody
    public Rest<?> XHzException(RestException ex){
            return ex.getStatus() == null ? Rest.ERROR(ex.getMsg()) : Rest.COMMON(ex.getStatus(),ex.getMsg());
    }
}
